package com.msb.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.AuthConstant;
import com.msb.common.dto.MemberDTO;
import com.msb.common.utils.HttpClientUtils;
import com.msb.common.utils.R;
import com.msb.mall.auth.feign.MemberFeignService;
import com.msb.common.dto.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 微博社交平台授权-获取token
     * @param code
     * @return
     */
    @RequestMapping("/weibo/success")
    public String weiboOAuth(@RequestParam("code") String code, HttpSession session){
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","2054002803");
        map.put("client_secret","a0216f93d6d79c90045f29100b1d72e8");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.msb.com/oauth/weibo/success");
        map.put("code",code);
        // 根据code获取对应的token信息
        String json = HttpClientUtils.doPost("https://api.weibo.com/oauth2/access_token", map);
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
        // token获取成功，获取用户信息入库，或更新
        R r = memberFeignService.oauthLogin(socialUser);
        if (r.getCode() != 0){
            // 登录错误
            return "redirect:http://auth.msb.com/login.html";
        }
        String memberEntity = JSON.toJSONString(r.get("memberEntity"));
        MemberDTO memberDTO = JSON.parseObject(memberEntity, MemberDTO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberDTO);
        System.out.println("---------------------->>登陆成功："+memberDTO.toString());
        return "redirect:http://mall.msb.com/index.html";
    }

}
